#include "OrderService.h"

// 获取订单
QJsonObject OrderService::getOrders(int userId)
{
    QJsonObject ordersJsonObject;

    QList<Order> orders = OrdersDataAccess::getOrders(userId);

    // 创建一个 JSON 数组来存储所有的订单
    QJsonArray orderJsonArray;
    for (const Order &order : orders)
    {
        QJsonObject orderJson;

        orderJson["order_id"] = order.orderId;
        orderJson["order_date"] = order.orderDate.toString(Qt::ISODate);
        orderJson["total_amount"] = order.totalAmount;
        orderJson["name"] = order.name;
        orderJson["phone"] = order.phone;
        orderJson["address"] = order.address;

        QList<OrderDetail> orderDetails = OrdersDataAccess::getOrderDetails(order.orderId);
        QJsonArray orderDetailJsonArray;
        for (const OrderDetail &orderDetail : orderDetails)
        {
            QJsonObject orderDetailJson;

            orderDetailJson["product_id"] = orderDetail.productId;
            orderDetailJson["quantity"] = orderDetail.quantity;
            orderDetailJson["price"] = orderDetail.price;

            orderDetailJsonArray.append(orderDetailJson);
        }

        orderJson["items"] = orderDetailJsonArray;

        orderJsonArray.append(orderJson);
    }

    ordersJsonObject["orders"] = orderJsonArray;

    return ordersJsonObject;
}

// 商品购买
bool OrderService::buy(QJsonObject &userOrder)
{
    // 解析用户ID和地址ID
    int userId = userOrder["user_id"].toInt();
    int addressId = userOrder["address_id"].toInt();

    // 获取地址详情
    Address address = AddressBookDataAccess::getAddressById(addressId);

    // 创建订单详情（商品）列表
    QList<OrderDetail> orderDetails;

    // 初始化总金额
    double totalAmount = 0;

    // 遍历订单中的每个商品
    QJsonArray itemsArray = userOrder["items"].toArray();
    for (const QJsonValue &itemValue : itemsArray)
    {
        // 获取商品ID和数量
        QJsonObject itemObject = itemValue.toObject();
        int productId = itemObject["product_id"].toInt();
        int quantity = itemObject["quantity"].toInt();
        // 获取商品详细信息
        Product product = ProductDataAccess::getProductById(productId);
        // 存入订单详情
        OrderDetail orderDetail;
        orderDetail.productId = productId;
        orderDetail.quantity = quantity;
        orderDetail.price = product.price;
        orderDetails.append(orderDetail);
        // 计算金额，存入总金额
        double price = product.price;
        totalAmount += price * quantity;
    }

    // 创建订单
    int orderId = OrdersDataAccess::creatOrder(userId, QDateTime::currentDateTime(), totalAmount, address.name, address.phone, address.address);
    // 添加订单详情
    for (const OrderDetail &orderDetail : orderDetails)
    {
        OrdersDataAccess::addOrderDetail(orderId, orderDetail.productId, orderDetail.quantity, orderDetail.price);
    }

    return true;
}
